import 'dart:async';
import 'package:flutter/material.dart';
import 'package:ycbl/common/EventBus.dart';
import 'package:ycbl/config/bl_constant.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/view_model/SearchViewModel.dart';
import 'package:ycbl/widget/ProductItemCell.dart';
import 'package:ycbl/widget/provider/bl_provider_widget.dart';
import 'package:ycbl/widget/refesh/bl_smart_refresher.dart';
import 'AutoComplete.dart';
import 'Suggestions.dart';

///SearchDelegate
class BLSearchDelegate1 extends SearchDelegate<String> {
  StreamSubscription _searchSubscription;

  @override
  String get searchFieldLabel => '请输入关键词';

  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [
      GestureDetector(
          onTap: () {
            close(context, null);
          },
          child:
          Container(
            padding: EdgeInsets.fromLTRB(16.5, 0.0, 14.5, 0.0),
            alignment: Alignment.center,
              child: Text("取消")
          )
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Container(child:Text(""));
  }

  @override
  Widget buildResults(BuildContext context) {
    // 取消搜索侦听
    _searchSubscription.cancel();
    // 简单显示搜索结果，并未真正去请求网络，后面文章会继续讲解如何通过api查询
    return BLProviderWidget<SearchViewModel>(
      notifierModel: SearchViewModel(BLConstant.BASE_API_URL +
          "?s=Ycsc.Com.Lists&tableId=353&pageId=6407&source=1&PRODUCT_NAME_2_andOr=0&PRODUCT_NAME_strCond_pld=0&PRODUCT_NAME_strVal_pld=$query"),
      onModelReady: (model) {
        LogUtil.e('onModelReady....');
        model.initData();
      },
      consumerBuilder: (context, searchModel, child) {
        return searchModel.simpleStateWidget(
          contentWidget: BLSmartRefresher(
            controller: searchModel.refreshController,
            onRefresh: () {
              LogUtil.d('onRefresh....');
              searchModel.refresh();
            },
            enablePullUp: true,
            onLoading: () {
              LogUtil.d('onLoadMore....');
              searchModel.loadMore();
            },
            child: ListView.builder(
              itemBuilder: (context, index) {
                LogUtil.d('itemBuilder.... $index');
                return ProductItemCell(
                  productCourse: searchModel.list[index].productCourse,
                  productName: searchModel.list[index].productName,
                  startDate: searchModel.list[index].startDate,
                  endDate: searchModel.list[index].endDate,
                  rnNumber: searchModel.list[index].rnNumber,
                  teacherHead: searchModel.list[index].teacherHead,
                  teacherName: searchModel.list[index].teacherName,
                  nowNumber: searchModel.list[index].nowNumber,
                  userIds:  searchModel.list[index].userIds,
                  productNowPrice: searchModel.list[index].productNowPrice,
                  productOldPrice: searchModel.list[index].productOldPrice,
                  allItemData: searchModel.list[index].allItemData,
                );
              },
              itemCount: searchModel?.list?.length ?? 0,
            ),
          ),
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // 事件侦听
    _searchSubscription = eventBus.on<SearchEvent>().listen((event) {
      this.popResults(context);
      this.setSearchKeyword(event.keywords);
    });

    /// 将方法作为参数传递给子组件调用，展示使用非EventBus方式通信
    return query.isEmpty
        ? Suggestions()
        : AutoComplete(query, this.popResults, this.setSearchKeyword);
  }

  /// 搜索结果展示
  void popResults(BuildContext context) {
    showResults(context);
  }

  /// 设置query
  Future<void> setSearchKeyword(String searchKeyword) async {
    query = searchKeyword;
  }
//  @override
//  ThemeData appBarTheme(BuildContext context) {
//    assert(context != null);
//    final ThemeData theme = Theme.of(context);
//    assert(theme != null);
//    return theme.copyWith(
//      primaryColor: Colors.white,
//      primaryIconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
//      primaryColorBrightness: Brightness.light,
//      primaryTextTheme: theme.textTheme,
//    );
//  }
}
